﻿using UnityEngine;
using System.Collections;

public class Enemy : MonoBehaviour 
{
	public GameObject m_fuelBarrel;
	private Vector3 m_directionToTarget;
	public float m_speed;
	private float m_turnSpeed = 1.0f;
	private Vector3 m_headingVector;
	private Vector3 m_oldPosition;
	public bool m_isAlive;
	private SceneManager m_sceneManager;
	// Use this for initialization
	void Start () 
	{
		m_isAlive = true;
		m_sceneManager = GameObject.Find("SceneManager").GetComponent<SceneManager>();
	}
	
	// Update is called once per frame
	void Update () 
	{
		if( !m_isAlive )
			return;

		Vector3 targetPosition = m_fuelBarrel.transform.position;
		targetPosition.x += 32.0f;
		targetPosition.y -= 32.0f;

		Debug.DrawLine(transform.position, transform.position + transform.right * 150.0f, Color.white);

		m_directionToTarget = targetPosition - transform.position;
		m_directionToTarget.Normalize();
		Debug.DrawLine(transform.position, targetPosition, Color.red);

		float fReqAngle = 0.0f;
		fReqAngle = GetAngle(m_directionToTarget, transform.right );

		m_directionToTarget = transform.right;

		if( m_oldPosition != targetPosition )
		{
			//Debug.Log("Req Angle : " + fReqAngle * Mathf.Rad2Deg);
			if( fReqAngle >= 10.0f && fReqAngle <= 70.0f )
			{
				Debug.Log("Smart calculation needed!!!");
			}

		}

		transform.Rotate(Vector3.forward, -fReqAngle * /*Time.deltaTime */ m_turnSpeed);
		transform.position += m_directionToTarget * m_speed * Time.deltaTime;

		m_oldPosition = targetPosition;
		
	}

	float GetAngle(Vector3 _v1, Vector3 _v2)
	{
		/*float fRadians = 0.0f;
		
		fRadians = Mathf.Atan2(_v1.x*_v2.y - _v1.y*_v2.x, _v1.x*_v2.x+_v1.y*_v2.y);
		return Mathf.Rad2Deg * fRadians * 1.0f;*/
		return Mathf.Atan2(Cross(_v1,_v2), Dot(_v1,_v2));
	}

	float Dot(Vector3 A, Vector3 B)
	{
		return A.x*B.x+A.y*B.y;
	}
	float Cross(Vector3 A, Vector3 B)
	{
		return A.x*B.y-A.y*B.x;
	}

	public void SetPosition(Vector3 _pos)
	{
		transform.position = _pos;
	}

	public void SetAlive(bool _alive)
	{
		m_isAlive = _alive;
	}

	void OnCollisionEnter2D(Collision2D coll) 
	{
		Debug.Log("Enemy hit " + coll.gameObject.tag);
		if( coll.gameObject.tag == "TargetPickup" )
		{

			SceneInformation.GetInstance().m_enemyScore += 1;
			//Hit by a Enemy, so destroy it
			Vector3 colPoint = transform.position;
			colPoint.x += 16.0f;
			colPoint.y -= 16.0f;
			m_sceneManager.ExplodeBarrel( colPoint );

		}
	}
}
